import React, { useEffect, useRef } from 'react';
import { Card, Table, Typography, Row, Col, Statistic } from 'antd';
import * as echarts from 'echarts';

const { Title, Text } = Typography;

// 模拟数据
const mockData = [
  { user_id: 'U001', view_count: 120, click_count: 85, cart_count: 30, purchase_count: 15, conversion_rate: 0.125 },
  { user_id: 'U002', view_count: 245, click_count: 120, cart_count: 50, purchase_count: 25, conversion_rate: 0.102 },
  { user_id: 'U003', view_count: 310, click_count: 180, cart_count: 75, purchase_count: 40, conversion_rate: 0.129 },
  { user_id: 'U004', view_count: 156, click_count: 95, cart_count: 35, purchase_count: 18, conversion_rate: 0.115 },
  { user_id: 'U005', view_count: 290, click_count: 150, cart_count: 60, purchase_count: 30, conversion_rate: 0.103 },
  { user_id: 'U006', view_count: 410, click_count: 220, cart_count: 90, purchase_count: 50, conversion_rate: 0.122 },
  { user_id: 'U007', view_count: 189, click_count: 110, cart_count: 45, purchase_count: 22, conversion_rate: 0.116 },
  { user_id: 'U008', view_count: 350, click_count: 190, cart_count: 80, purchase_count: 42, conversion_rate: 0.120 },
  { user_id: 'U009', view_count: 210, click_count: 130, cart_count: 55, purchase_count: 28, conversion_rate: 0.133 },
  { user_id: 'U010', view_count: 270, click_count: 140, cart_count: 65, purchase_count: 35, conversion_rate: 0.130 },
  { user_id: 'U011', view_count: 320, click_count: 170, cart_count: 70, purchase_count: 38, conversion_rate: 0.119 },
  { user_id: 'U012', view_count: 240, click_count: 125, cart_count: 55, purchase_count: 28, conversion_rate: 0.117 },
];

// 定义表格列
const columns = [
  {
    title: '用户ID',
    dataIndex: 'user_id',
    key: 'user_id',
  },
  {
    title: '浏览次数',
    dataIndex: 'view_count',
    key: 'view_count',
  },
  {
    title: '点击次数',
    dataIndex: 'click_count',
    key: 'click_count',
  },
  {
    title: '购物车添加次数',
    dataIndex: 'cart_count',
    key: 'cart_count',
  },
  {
    title: '购买次数',
    dataIndex: 'purchase_count',
    key: 'purchase_count',
  },
  {
    title: '转化率',
    dataIndex: 'conversion_rate',
    key: 'conversion_rate',
    render: (text) => `${(text * 100).toFixed(2)}%`,
  },
];

const PurchaseRateTable = () => {
  const barChartRef = useRef(null);
  const scatterChartRef = useRef(null);
  const barChartInstance = useRef(null);
  const scatterChartInstance = useRef(null);

  useEffect(() => {
    // 初始化柱状图
    if (barChartRef.current && !barChartInstance.current) {
      barChartInstance.current = echarts.init(barChartRef.current);
    }

    // 初始化散点图
    if (scatterChartRef.current && !scatterChartInstance.current) {
      scatterChartInstance.current = echarts.init(scatterChartRef.current);
    }

    // 准备柱状图数据
    const barData = mockData.sort((a, b) => b.conversion_rate - a.conversion_rate);
    const userIds = barData.map(item => item.user_id);
    const conversionRates = barData.map(item => (item.conversion_rate * 100).toFixed(2));
    const purchaseCounts = barData.map(item => item.purchase_count);

    // 准备散点图数据
    const scatterData = mockData.map(item => [item.view_count, (item.conversion_rate * 100).toFixed(2), item.user_id]);

    // 柱状图配置
    const barOption = {
      title: {
        text: '用户转化率排行',
        left: 'center'
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        },
        formatter: function(params) {
          const dataIndex = params[0].dataIndex;
          const userData = barData[dataIndex];
          return `用户ID: ${userData.user_id}<br/>` +
                 `转化率: ${(userData.conversion_rate * 100).toFixed(2)}%<br/>` +
                 `浏览次数: ${userData.view_count}<br/>` +
                 `购买次数: ${userData.purchase_count}`;
        }
      },
      legend: {
        data: ['转化率(%)', '购买次数'],
        bottom: 10
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '15%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: userIds,
        axisLabel: {
          interval: 0,
          rotate: 45
        }
      },
      yAxis: [
        {
          type: 'value',
          name: '转化率(%)',
          position: 'left',
        },
        {
          type: 'value',
          name: '购买次数',
          position: 'right',
        }
      ],
      series: [
        {
          name: '转化率(%)',
          type: 'bar',
          data: conversionRates,
          itemStyle: {
            color: '#5470c6'
          }
        },
        {
          name: '购买次数',
          type: 'line',
          yAxisIndex: 1,
          data: purchaseCounts,
          itemStyle: {
            color: '#91cc75'
          }
        }
      ]
    };

    // 散点图配置
    const scatterOption = {
      title: {
        text: '浏览量与转化率关系',
        left: 'center'
      },
      tooltip: {
        trigger: 'item',
        formatter: function(params) {
          const dataIndex = params.dataIndex;
          const userData = scatterData[dataIndex];
          return `用户ID: ${userData[2]}<br/>` +
                 `浏览次数: ${userData[0]}<br/>` +
                 `转化率: ${userData[1]}%`;
        }
      },
      xAxis: {
        type: 'value',
        name: '浏览次数',
        splitLine: {
          lineStyle: {
            type: 'dashed'
          }
        }
      },
      yAxis: {
        type: 'value',
        name: '转化率(%)',
        splitLine: {
          lineStyle: {
            type: 'dashed'
          }
        }
      },
      series: [
        {
          type: 'scatter',
          data: scatterData,
          symbolSize: 8,
          itemStyle: {
            color: '#fac858'
          },
          emphasis: {
            itemStyle: {
              color: '#ee6666'
            },
            symbolSize: 12
          }
        }
      ]
    };

    // 渲染图表
    if (barChartInstance.current) {
      barChartInstance.current.setOption(barOption);
    }
    if (scatterChartInstance.current) {
      scatterChartInstance.current.setOption(scatterOption);
    }

    // 响应式调整
    const handleResize = () => {
      if (barChartInstance.current) {
        barChartInstance.current.resize();
      }
      if (scatterChartInstance.current) {
        scatterChartInstance.current.resize();
      }
    };

    window.addEventListener('resize', handleResize);

    return () => {
      window.removeEventListener('resize', handleResize);
      if (barChartInstance.current) {
        barChartInstance.current.dispose();
        barChartInstance.current = null;
      }
      if (scatterChartInstance.current) {
        scatterChartInstance.current.dispose();
        scatterChartInstance.current = null;
      }
    };
  }, []);

  // 计算统计信息
  const totalViews = mockData.reduce((sum, item) => sum + item.view_count, 0);
  const totalPurchases = mockData.reduce((sum, item) => sum + item.purchase_count, 0);
  const averageConversionRate = totalPurchases / totalViews;
  const maxConversionRate = Math.max(...mockData.map(item => item.conversion_rate));
  const minConversionRate = Math.min(...mockData.map(item => item.conversion_rate));

  return (
    <div>
      <Title level={4}>购买转化率分析</Title>
      <Row gutter={[16, 16]}>
        <Col xs={24} lg={8}>
          <Card>
            <Title level={5}>转化率统计</Title>
            <Row gutter={16}>
              <Col span={12}>
                <Statistic 
                  title="平均转化率" 
                  value={(averageConversionRate * 100).toFixed(2)} 
                  suffix="%"
                  precision={2}
                  valueStyle={{ color: '#3f8600' }}
                />
              </Col>
              <Col span={12}>
                <Statistic 
                  title="最高转化率" 
                  value={(maxConversionRate * 100).toFixed(2)} 
                  suffix="%"
                  precision={2}
                  valueStyle={{ color: '#cf1322' }}
                />
              </Col>
              <Col span={12}>
                <Statistic 
                  title="最低转化率" 
                  value={(minConversionRate * 100).toFixed(2)} 
                  suffix="%"
                  precision={2}
                  valueStyle={{ color: '#1890ff' }}
                />
              </Col>
              <Col span={12}>
                <Statistic 
                  title="总浏览量" 
                  value={totalViews}
                  precision={0}
                  valueStyle={{ color: '#faad14' }}
                />
              </Col>
            </Row>
          </Card>
        </Col>
        <Col xs={24} lg={16}>
          <Card>
            <div ref={barChartRef} style={{ width: '100%', height: 300 }} />
          </Card>
        </Col>
        <Col span={24}>
          <Card>
            <div ref={scatterChartRef} style={{ width: '100%', height: 400 }} />
          </Card>
        </Col>
      </Row>
      <Card style={{ marginTop: 20 }}>
        <Title level={5}>详细数据列表</Title>
        <Table columns={columns} dataSource={mockData} rowKey="user_id" pagination={{ pageSize: 10 }} />
      </Card>
    </div>
  );
};

export default PurchaseRateTable;